import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入路由组件
import Reg from '@/views/Reg.vue'
import Login from '@/views/Login.vue'
import Main from '@/views/Main.vue'
import Home from '@/views/Menus/Home.vue'
import UserInfo from '@/views/Menus/User/info.vue'
import UserAvatar from '@/views/Menus/User/Avatar.vue'
import UserPwd from '@/views/Menus/User/Pwd.vue'
import store from '@/store/'
Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    // 注册页面的路由规则
    { path: '/reg', component: Reg },
    // 登录页面的路由规则
    { path: '/login', component: Login },
    // 后台主页的路由规则
    {
      path: '/',
      component: Main,
      redirect: '/home',
      children: [
        // 子路由规则
        // path: '/home' 是完整的写法"父+子"
        // path: 'home'是筒写形式, 吧父 path 给省略了,而且子路由的path 不能以 / 开头
        { path: 'home', component: Home },
        { path: 'user-info', component: UserInfo },
        { path: 'user-avatar', component: UserAvatar },
        { path: 'user-pwd', component: UserPwd }
      ]
    }
  ]
})
// 声明全局前置守卫
router.beforeEach((to, from, next) => {
  if (to.path === '/login' || to.path === '/reg') {
    next()
  } else {
    const token = store.state.user.token
    if (token) {
      // token 有值 放行
      next()
    } else {
      // 没有 token 则强制跳转到登录页面
      next('/login')
    }
  }
})

export default router
